package com.hzqy.commons.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzqy.commons.service.utils.ServiceUtils;
import com.hzqy.commons.utils.MD5Util;
import com.hzqy.web.vo.AuthenticatedVo;
import com.hzqy.web.vo.SysProductVo;

public class AuthenticatedService {
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	private ServiceUtils serviceUtils = null;
	private HttpServletRequest request;
	
	public AuthenticatedService(HttpServletRequest req, HttpServletResponse response) {
		this.request = req;
		String cookiesValue = null;
		Cookie[] cookies = req.getCookies();
		for(int i = 0; i < cookies.length; i++) {
			//LOG.debug("cookies"+i+"=name="+cookies[i].getName()+"=value="+cookies[i].getValue());
			if(cookies[i].getName() != null && cookies[i].getName().equals("JSESSIONID")) {
				cookiesValue = cookies[i].getName()+"="+cookies[i].getValue();
				break;
			}
		}
		serviceUtils = new ServiceUtils(cookiesValue);
	}
	
	/**
	 * 根据服务id鉴权
	 * @param serverid
	 * @param serviceCode
	 * @param readTimeOut
	 * @param connectTimeout
	 * @return
	 */
	public String getAuthenticatedResult(String serverid,String serviceCode,int readTimeOut,int connectTimeout){
		String result = "";
		if(serviceCode!=null && serviceCode.trim().startsWith("test")) { //防止在做组合产品包时没有服务ID还发起鉴权，所以碰到test打头的产品包ID或者服务ID时不发起鉴权直接返回未定购504
			result = "504"; //未定购504
			LOG.debug("未发起鉴权，因为服务ID是test打头=serviceCode="+serviceCode);
		} else {
			result = String.valueOf(request.getSession().getAttribute(serverid+serviceCode)); //为了减少订购用户的鉴权次数，将鉴权结果存入session
			if(result==null || !result.equals("0")) {
				result = serviceUtils.getServiceResult(serverid, serviceCode, readTimeOut, connectTimeout);
				request.getSession().setAttribute(serverid+serviceCode,result);
			} else {
				LOG.debug("未发起鉴权，因为"+serverid+"服务ID是serviceCode="+serviceCode+"session值为"+result);
			}
		}
		if("-1".equals(result)) {//服务鉴权失败
			LOG.error("鉴权失败! 服务异常，返回="+result);
		}else{
			LOG.debug("服务鉴权返回结果："+result+",userId="+serverid+",serviceid="+serviceCode);
		}
		return result;
	}
	
	/**
	 * 根据产品id鉴权
	 * @param serverid
	 * @param productCode
	 * @param readTimeOut
	 * @param connectTimeout
	 * @return
	 */
	public String getAuthenticatedResultByProductID(AuthenticatedVo authVo){
		String result = "";
		if(authVo.getProductCode()!=null && authVo.getProductCode().trim().startsWith("test")) { //防止在做组合产品包时没有服务ID还发起鉴权，所以碰到test打头的产品包ID或者服务ID时不发起鉴权直接返回未定购504
			result = "504"; //未定购504
			LOG.debug("未发起鉴权，因为产品ID是test打头=productCode="+authVo.getProductCode());
		} else {
			String authenticatedResultKey = authVo.getServerid()+authVo.getProductCode();
			String contentId = authVo.getContentId();
			if(!"".equals(contentId)&&contentId!=null&&!"undefined".equals(contentId)){
				authenticatedResultKey += contentId;
			}
			result = String.valueOf(request.getSession().getAttribute(authenticatedResultKey)); //为了减少订购用户的鉴权次数，将鉴权结果存入session
			if(result==null || !result.equals("0")) {
				result = serviceUtils.getServiceResultByProductID(authVo);
				request.getSession().setAttribute(authenticatedResultKey,result);
			} else {
				LOG.debug("未发起鉴权，因为"+authVo.getServerid()+"产品ID是productCode="+authVo.getProductCode()+",媒资ID是contentId=" +authVo.getContentId()+ ",session值为"+result);
			}
		}
		if("-1".equals(result)) {//服务鉴权失败
			LOG.error("鉴权失败! 服务异常，返回="+result);
		}else{
			LOG.debug("服务鉴权返回结果："+result+",userId="+authVo.getServerid()+",productCODE="+authVo.getProductCode()+",contentId="+authVo.getContentId());
		}
		return result;
	}
	
	public String getServiceAuthenticatedResultByContentID(String serverid,String serviceCode,String contendID,int readTimeOut,int connectTimeout){
		String result = "";
		if(serviceCode!=null && serviceCode.trim().startsWith("test")) { //防止在做组合产品包时没有服务ID还发起鉴权，所以碰到test打头的产品包ID或者服务ID时不发起鉴权直接返回未定购504
			result = "504"; //未定购504
			LOG.debug("未发起鉴权，因为服务ID是test打头=serviceCode="+serviceCode);
		} else {
			result = serviceUtils.getServiceResultByContendID(serverid, serviceCode, contendID, readTimeOut, connectTimeout);
		}
		if("-1".equals(result)) {//服务鉴权失败
			LOG.error("鉴权失败! 服务异常，返回="+result);
		}else{
			LOG.debug("服务鉴权返回结果："+result+",userId="+serverid+",serviceid="+serviceCode);
		}
		return result;
	}
	
	public String getProductAuthenticatedResultByContentID(String serverid,String serviceCode,String contendID,int readTimeOut,int connectTimeout){
		String result = "";
		if(serviceCode!=null && serviceCode.trim().startsWith("test")) { //防止在做组合产品包时没有服务ID还发起鉴权，所以碰到test打头的产品包ID或者服务ID时不发起鉴权直接返回未定购504
			result = "504"; //未定购504
			LOG.debug("未发起鉴权，因为服务ID是test打头=serviceCode="+serviceCode);
		} else {
			result = serviceUtils.getProductResultByContendID(serverid, serviceCode, contendID, readTimeOut, connectTimeout);
		}
		if("-1".equals(result)) {//服务鉴权失败
			LOG.error("鉴权失败! 服务异常，返回="+result);
		}else{
			LOG.debug("服务鉴权返回结果："+result+",userId="+serverid+",serviceid="+serviceCode);
		}
		return result;
	}
	
	/**
	 * 用户已订购产品详情
	*/
	public String getProductsOrdered(String userId) {
		Integer readTimeOut = 3000;
		Integer connectTimeout = 3000;
		String result = serviceUtils.getProductResultByunionProductId(userId,readTimeOut,connectTimeout);
		return result;
	}
	/**
	*根据提供的渠道号查询用户相对应的已订购产品详情	
	 */
	public String getOrderedProductsBychannelCode(AuthenticatedVo authVo,String server_channelCode,String server_channelCode_pwd) {
		String result = serviceUtils.getOrderedProductsBychannelCode(authVo,server_channelCode,server_channelCode_pwd);
		return result;
	}
	/**
	 * 
	 * @param authVo
	 * @param productList 由于教育和畅想乐园服务那边配置在一起，需要根据鉴权返回的结果判断下订购的属于哪个总包
	 * @return
	 */
	public Map<Object, Object> getAuthenticatedResultByBatchInterface(AuthenticatedVo authVo,List<SysProductVo> productList) {
		Map<Object, Object> resMap = new HashMap<>();
		String result = String.valueOf(request.getSession().getAttribute(authVo.getServerid()+authVo.getProductCode())); 
		// 为了减少订购用户的鉴权次数,将鉴权结果存入session
		try {
			if(result==null || !result.equals("0")) {
				String batchauthresult = serviceUtils.getServiceResultByBatchInterface(authVo);
				resMap.put("batchauthresult", batchauthresult);
				JSONObject jsonObject = JSONObject.parseObject(batchauthresult);
				JSONArray orderpros = (JSONArray) jsonObject.get("products");
				//LOG.debug("通过批量鉴权接口鉴权结果:"+batchauthresult);
				//LOG.debug("通过批量鉴权接口鉴权结果-orderpros.size():"+orderpros.size());
				if(orderpros.size()>0) {
					for(int i=0;i<orderpros.size();i++) {
						JSONObject jObject = (JSONObject) orderpros.get(i);
						String productId = jObject.getString("productId");
						for(int j=0;j<productList.size();j++) {
							String dbproductcode = productList.get(j).getF_sp_productcode();
							if(dbproductcode.equals(productId)) {
								LOG.debug("批量鉴权接口-========:"+dbproductcode);
								result = "0";
								break;
							}
						}
					}
					if(result==null || !result.equals("0")) {
						result = "504";
					}
				}else {
					result = "504";
				}
				request.getSession().setAttribute(authVo.getServerid()+authVo.getProductCode()+"batchauthresult",batchauthresult);
				request.getSession().setAttribute(authVo.getServerid()+authVo.getProductCode(),result);
			} else {
				String batchauthresult =  (String) request.getSession().getAttribute(authVo.getServerid()+authVo.getProductCode()+"batchauthresult");
				resMap.put("batchauthresult", batchauthresult);
				LOG.debug("未发起鉴权，因为"+authVo.getServerid()+"产品ID是productCode="+authVo.getProductCode()+"session值为"+result+"batchauthresult:"+batchauthresult);
			}
		}catch (Exception e) {
			result = "-1";
			LOG.error("通过批量鉴权接口鉴权失败:",e);
		}
		resMap.put("result", result);
		return resMap;
	}
	
	/*
	public String getOrderResult(String SPID,String productCode,String serverid,String partner,String epg_info,int readTimeOut,int connectTimeout) {
		String Result = "";
		String serviceResult = map.get(serverStatus);
		
		if("normal".equals(serviceResult)) {
			Result = serviceUtils.getOrderResult(SPID, productCode, serverid, partner, epg_info, readTimeOut, connectTimeout);
			if("-1".equals(Result)) {//服务鉴权失败
				LOG.debug("鉴权失败! 服务异常");
				return "error";
			}else{
				if("0".equals(Result)) {
					map.put(Integer.valueOf(productCode), Result);
					session.setAttribute("OrderMap_"+serverid, map);
				}
				LOG.debug("订购返回结果："+Result+",userId="+serverid+",productCode="+productCode);
				return Result;
			}
		}else {//服务异常
			LOG.debug("订购返回结果:服务异常!");
			return "error";
		}
		
	}
	*/
}
